import { Modal } from 'antd';
import { WeaTools } from "ecCom";
const getKey = WeaTools.getKey;
import isEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

export const transfStr = (name = '', ids = '', list = [], type = '') => {
	let str = '';
	const mirror = {
		37: "doc",
		prjtsk: "task",
		18: "crm",
		152: "workflow",
		135: "project",
	}
	list.map(item => {
		if (name === 'Upload' && type === 'image') {
			str += '<img class="formImgPlay" src="' + item.filelink + '" data-imgsrc="' + (item.loadlink || item.filelink) + '" />'
		}
		if (name === 'Upload' && type === 'file') {
			str += (`<a href='javascript:void(0)'  style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a><br>`)
		}
		if (name === 'Browser') {
			str += (`<a href='javascript:void(0)'  style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a><br>`)
		}
	})
	return str
}

export const getFormInitDatas = (condition = []) => {
	let initdatas = {};
	condition.map(c => {
		let items = [];
		c.items.map((field, index) => {
			const key = getKey(field);
			if (field.conditionType == "BROWSER") {
				if (!isEmpty(field.browserConditionParam)) {
					const replacesDatas = field.browserConditionParam.replaceDatas || field.browserConditionParam.valueObj;
					if (!isEmpty(replacesDatas)) {
						let values = [], names = [];
						replacesDatas.forEach((d) => {
							values.push(d.id);
							names.push(d.lastname || d.name); // 人力按钮特殊处理
						});
						initdatas[key] = {
							value: values.join(','),
							valueSpan: names.join(','),
							valueObj: replacesDatas
						}
					}
				}
			} else if (field.conditionType == 'DATE') {
				let selectValue = '0', startValue = null, endValue = null;
				if (!isEmpty(field.options)) selectValue = WeaTools.getSelectDefaultValue(field.options) || selectValue;
				if (!isEmpty(field.value)) {
					selectValue = field.value[field.domkey[0]];
					startValue = field.value[field.domkey[1]];
					endValue = field.value[field.domkey[2]];
				}
				initdatas[key] = {
					value: [selectValue, startValue, endValue]
				}
			} else if (field.conditionType == 'SELECT') {
				let value = WeaTools.getSelectDefaultValue(field.options);
				if (field.value !== undefined) value = field.value;
				if (value !== undefined) {
					initdatas[key] = {
						value: value
					}
				}
			} else if (field.conditionType == 'SELECT_LINKAGE') {
				let selectValue = WeaTools.getSelectDefaultValue(field.options) || '0';
				initdatas[key] = {
					value: [selectValue]
				}
			} else if (field.conditionType == "SCOPE") {
				let sValue = field.startValue || '', eValue = field.endValue || '';
				initdatas[key] = {
					value: [sValue, eValue]
				}
			} else if (field.conditionType == 'RANGEPICKER') {
				let sValue = field.startDate || field[field.domkey[0]] || '', eValue = field.endDate || field[field.domkey[1]] || '';
				initdatas[key] = {
					value: [sValue, eValue]
				}
			} else {

				initdatas[key] = { value: field.value || "" };
			}

		});
	});
	return initdatas;
}

export const datediff = (sDate1, sDate2, sDate3, sDate4, manager, passnoworktime) => {
	var aDate, oDate1, oDate2, iDays, odate3, odate4, tdate, otime1, otime2, oDatetime1, oDatetime2;

	if (passnoworktime != 1) {

		oDate1 = new Date(sDate1);
		oDate2 = new Date(sDate2);
		odate3 = new Date(sDate3);
		odate4 = new Date(sDate4);

		if (true || "" + oDate1.getFullYear() == "NaN") {
			aDate = sDate1.split("-")
			tdate = sDate3.split(":")
			oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])   //转换为12-18-2002格式
			oDatetime1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0] + " " + tdate[0] + ":" + tdate[1])

			aDate = sDate2.split("-")
			tdate = sDate4.split(":")
			oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
			oDatetime2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0] + " " + tdate[0] + ":" + tdate[1])

		}
		if (oDate2 - oDate1 < 0) {
			iDays = -1 	//日期
		} else if (oDate2 - oDate1 == 0) {
			if (sDate4 < sDate3) {
				iDays = -2 //时间
			} else {
				iDays = (Math.abs(oDatetime1 - oDatetime2) / 1000 / 60 / 60 / 24).toFixed(2)
			}
		} else {
			iDays = (Math.abs(oDatetime1 - oDatetime2) / 1000 / 60 / 60 / 24).toFixed(2)
		}
	} else {   //计算去掉不包含非工作日

		$.ajax({
			type: "post",
			url: "/proj/process/GetWorkDays.jsp",
			data: "begindate=" + sDate1 + "&begintime=" + sDate3 + "&enddate=" + sDate2 + "&endtime=" + sDate4 + "&manager=" + manager,
			dataType: "text",
			async: false,
			success: function (data) {
				iDays = data.trim();
			}
		});
	}

	return iDays;

}

export const openWindow = url => {
	const width = screen.availWidth - 10;
	const height = screen.availHeight - 50;
	let szFeatures = 'top=0,';
	szFeatures += 'left=0,';
	szFeatures += `width=${width},`;
	szFeatures += `height=${height},`;
	szFeatures += 'directories=no,';
	szFeatures += 'status=yes,toolbar=no,location=no,';
	szFeatures += 'menubar=no,';
	szFeatures += 'scrollbars=yes,';
	szFeatures += 'resizable=yes';
	window.open(url, '', szFeatures);
};

window.openFullWindowHaveBar = openWindow;
window.openFullWindowForXtable = openWindow;

window.prjOpenPage = function (routeUrl) {
	window.open("/spa/prj/index.html#" + routeUrl, "_blank");
}

//打开附件
window.openProjectDiscussDoc = (t, showid, prjid,auth_url) => {
	openFullWindowHaveBar(`/spa/document/index2file.jsp?id=${showid}&isOpenFirstAss=1&prjid=${prjid}${auth_url}`)
}
//打开附件
window.openProjectDiscussDownload = (t, showid, prjid,auth_url) => {
	window.open(`/weaver/weaver.file.FileDownload?fileid=${showid}&download=1&prjid=${prjid}${auth_url}`)
}

window.openProjectAppLink = (linkType, linkid, prjid,auth_url) => {
	if (linkType == 'doc')
	  window.open(`/spa/document/index.jsp?id=${linkid}&prjid=${prjid}${auth_url}`)
	else if (linkType == 'task')
	  window.open(`/spa/prj/index.html#/main/prj/taskCard?taskid=${linkid}`)
	else if (linkType == 'crm')
	  window.open(`/spa/crm/static/index.html#/main/crm/customerView?customerId=${linkid}`)
	else if (linkType == 'workflow')
	  window.open(`/spa/workflow/static4form/index.html#/main/workflow/req?fromModul=meeting&modulResourceId=${prjid}&requestid=${linkid}${auth_url}`)
	else if (linkType == 'project')
	  window.open(`/spa/prj/index.html#/main/prj/projectCard?prjid=${linkid}`)
	else
	  return false
  }

// openFullWindowForXtable("/spa/proj/index.html#/main/proj/taskCard?taskid="+1)  //标签页打开
// prjOpenPage("/main/proj/taskCard?taskid="+1)   //新窗口打开

export const cptAddFormRules = (condition = []) => {
	condition.map(c => {
		let items = [];
		c.items.map((field, index) => {
			if (field.conditionType == "BROWSER") {
				if (field.browserConditionParam.viewAttr == "3") {
					field.rules = 'required|string'// 校验规则
				}
			} else {
				if (field.viewAttr == "3") {
					field.rules = 'required|string'// 校验规则
				}
			}
		})
	});
	return condition;
}

export const changeToThousand = (s) => {//千分位显示  
	if (s && s.toString().indexOf('-') == 0) {
		if (isNaN(s)) {//js自己的方法检验数字  
			return s;
		} else {
			s = parseFloat(s);//去除首位输入的0，如002，小数不影响parseFloat字符串转数字  
			s = s.toString().replace('-', "");
			s = s.replace(/^(\d*)$/, "$1.");
			s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
			s = s.replace(".", ",");
			var re = /(\d)(\d{3},)/;
			while (re.test(s))
				s = s.replace(re, "$1,$2");
			s = s.replace(/,(\d\d)$/, ".$1");
			return '-' + s.replace(/^\./, "0.");
		}
	} else {
		if (isNaN(s)) {//js自己的方法检验数字  
			return s;
		} else {
			s = parseFloat(s);//去除首位输入的0，如002，小数不影响parseFloat字符串转数字  
			s = s.toString();
			s = s.replace(/^(\d*)$/, "$1.");
			s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
			s = s.replace(".", ",");
			var re = /(\d)(\d{3},)/;
			while (re.test(s))
				s = s.replace(re, "$1,$2");
			s = s.replace(/,(\d\d)$/, ".$1");
			return s.replace(/^\./, "0.");
		}
	}
} 

export function judgeIsNumber(val) {
	if (val === null || typeof val === "undefined")
		return false;
	const reg = /^(-?\d+)(\.\d+)?$/;
	return reg.test(val.toString());
}

export const convertFloatValue = (realval, decimals, transQfw, transAbs) => {  //值  位数  是否转换千分位  绝对值
	if (!judgeIsNumber(realval))     //非数值直接返回原始值
		return realval;
	realval = realval.toString();
	var formatval = "";
	if (decimals === 0) {		//需取整
		formatval = Math.round(parseFloat(realval)).toString();
	} else {
		var n = Math.pow(10, decimals);
		formatval = (Math.round(parseFloat(realval) * n) / n).toString();
		var pindex = formatval.indexOf(".");
		var pointLength = pindex > -1 ? formatval.substr(pindex + 1).length : 0;	//当前小数位数
		if (decimals > pointLength) {		//需补零
			if (pindex == -1)
				formatval += ".";
			for (var i = 0; i < decimals - pointLength; i++) {
				formatval += "0";
			}
		}
	}
	var index = formatval.indexOf(".");
	var intPar = index > -1 ? formatval.substring(0, index) : formatval;
	var pointPar = index > -1 ? formatval.substring(index) : "";
	//取绝对值
	if (transAbs === true) {		//取绝对值
		intPar = Math.abs(intPar).toString();
	}
	if (transQfw === true) {				//整数位format成千分位
		var reg1 = /(-?\d+)(\d{3})/;
		while (reg1.test(intPar)) {
			intPar = intPar.replace(reg1, "$1,$2");
		}
	}
	formatval = intPar + pointPar;
	return formatval;
}

export const imgZoom = (dom, parentSelector) => {
	let imgList = jQuery(parentSelector + " img",dom);
	imgList.each((index,img) => {
	  let $img = $(img);
	  if ($img.attr("resize")) {
		return;
	  }
	  if ($img.parents(".ui-coomixPic").length > 0) {
		return;
	  }
	  $img.css({"max-width": "400px", "max-height" : "400px"}).attr("resize", 1).coomixPic({
		path:'/blog/js/weaverImgZoom/images',
		preload:true,
		blur: true,
		left: getLabel(26921, '向左转'),
		right: getLabel(26922, '向右转'),
		source: getLabel(26923, '查看原图'),
		hide: getLabel(26985, '收起')
	  });
	});
  };